package com.yanqu.road.server.cmd.assistant;

import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.assistant.AssistantProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.HouseModule;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Cmd(code = GameProtocol.S_ASSISTANT_BANK_BAR_SET, desc = "小助理钱庄设置")
public class AssistantBankBarSetCmd extends AbstractCommand {

    private List<Integer> dispatchPatronsList = new ArrayList<>();

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        AssistantProto.AssistantBankBarSetReqMsg reqMsg = AssistantProto.AssistantBankBarSetReqMsg.parseFrom(packet.getBytes());
        dispatchPatronsList = reqMsg.getPatronsListList();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        Set<Integer> patronsSet = new HashSet<>();
        PatronsModule patronsModule = player.getModule(PatronsModule.class);
        for (Integer patronsId : dispatchPatronsList) {
            // 名单重复
            if (!patronsSet.add(patronsId)) {
                ret = GameErrorCode.E_HOUSE_BAR_PATRONS_IS_DISPATCH;
                return;
            }
            UserPatrons userPatrons = patronsModule.getUserPatrons(patronsId);
            // 门客不存在
            if(userPatrons == null){
                ret = GameErrorCode.E_PATRONS_NO_FOUND;
                return;
            }
        }
        // 设置派遣名单
        player.getModule(HouseModule.class).setDispatchPatronsList(dispatchPatronsList);

        // 同步
        player.getModule(HouseModule.class).syncUserHouseBank();
    }

    @Override
    public void sendData(GamePlayer player) {
        AssistantProto.AssistantBankBarSetRespMsg.Builder respMsg = AssistantProto.AssistantBankBarSetRespMsg.newBuilder();
        respMsg.setRet(ret);
        player.sendPacket(ClientProtocol.U_ASSISTANT_BANK_BAR_SET, respMsg);
    }
}
